import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import api from '../utils/api';
import { RequestError } from '../utils/request';
import { userStorage } from '../utils/storage';
import './CreateCourse.css';

function CreateCourse() {
  const navigate = useNavigate();
  const location = useLocation();
  const [courseName, setCourseName] = useState('');
  const [courseIntro, setCourseIntro] = useState('');
  const [studentPhones, setStudentPhones] = useState(['']); // 初始一个空输入框
  const [creating, setCreating] = useState(false);

  // 当路由切换到创建课程页面时，重置表单状态
  useEffect(() => {
    if (location.pathname === '/main/create-course') {
      setCourseName('');
      setCourseIntro('');
      setStudentPhones(['']);
      setCreating(false);
    }
  }, [location.pathname]);

  // 添加学生电话输入框
  const handleAddPhone = () => {
    setStudentPhones([...studentPhones, '']);
  };

  // 删除学生电话输入框
  const handleRemovePhone = (index) => {
    if (studentPhones.length > 1) {
      const newPhones = studentPhones.filter((_, i) => i !== index);
      setStudentPhones(newPhones);
    }
  };

  // 更新学生电话
  const handlePhoneChange = (index, value) => {
    const newPhones = [...studentPhones];
    newPhones[index] = value;
    setStudentPhones(newPhones);
  };

  // 立即创建
  const handleCreate = async () => {
    // 验证表单
    if (!courseName.trim()) {
      alert('请输入课程名称');
      return;
    }
    if (!courseIntro.trim()) {
      alert('请输入课程简介');
      return;
    }

    setCreating(true);

    try {
      // 1. 获取用户信息（teacherPhone）
      const userInfo = userStorage.getUserInfo();
      if (!userInfo) {
        alert('未获取到用户信息，请重新登录');
        navigate('/login');
        return;
      }

      const teacherPhone = userInfo.phone;

      if (!teacherPhone) {
        console.log("teacherPhone!!!", teacherPhone);
        alert('用户手机号不存在，请重新登录');
        navigate('/login');
        return;
      }

      // 2. 过滤掉空的电话号码
      const validPhones = studentPhones.filter(phone => phone.trim() !== '');

      // 3. 准备接口参数
      const createCourseData = {
        teacherPhone: teacherPhone,
        courseName: courseName.trim(),
        courseDesc: courseIntro.trim(),
        courseMembers: validPhones
      };

      console.log('准备创建课程，参数:', createCourseData);

      // 4. 调用创建课程接口
      const result = await api.course.createCourse(createCourseData);

      console.log('课程创建成功:', result);

      // 5. 跳转到上传课程页面，并传递接口返回值
      navigate('/main/upload-course', {
        replace: true,
        state: {
          courseData: result, // 接口返回的课程数据
          courseName: courseName,
          courseIntro: courseIntro,
          studentPhones: validPhones
        }
      });

    } catch (error) {
      setCreating(false);

      if (error instanceof RequestError) {
        console.error('创建课程失败:', error.message);
        // 错误已由 request 自动显示
      } else {
        console.error('创建课程失败:', error);
      }
    }
  };

  return (
    <div className="create-course-container">
      <div className="create-course-box">
        <h2>创建课程（基本信息）</h2>
        
        <div className="form-section">
          <div className="form-group">
            <label className="required">课程名称</label>
            <input
              type="text"
              value={courseName}
              onChange={(e) => setCourseName(e.target.value)}
              placeholder="请输入课程名称"
              maxLength="50"
            />
          </div>

          <div className="form-group">
            <label className="required">课程简介</label>
            <textarea
              value={courseIntro}
              onChange={(e) => setCourseIntro(e.target.value)}
              placeholder="请输入课程简介"
              rows="4"
              maxLength="500"
            />
          </div>

          <div className="form-group">
            <label>参课学生电话</label>
            <div className="phone-list">
              {studentPhones.map((phone, index) => (
                <div key={index} className="phone-item">
                  <input
                    type="tel"
                    value={phone}
                    onChange={(e) => handlePhoneChange(index, e.target.value)}
                    placeholder="请输入学生手机号"
                    maxLength="11"
                  />
                  {studentPhones.length > 1 && (
                    <button
                      type="button"
                      className="remove-btn"
                      onClick={() => handleRemovePhone(index)}
                    >
                      删除
                    </button>
                  )}
                </div>
              ))}
            </div>
            <button
              type="button"
              className="add-phone-btn"
              onClick={handleAddPhone}
            >
              + 添加学生电话
            </button>
          </div>
        </div>

        <div className="form-actions">
          <button
            type="button"
            className="cancel-btn"
            onClick={() => navigate('/main/course')}
          >
            取消
          </button>
          <button
            type="button"
            className="submit-btn"
            onClick={handleCreate}
            disabled={creating}
          >
            {creating ? '创建中...' : '立即创建'}
          </button>
        </div>
      </div>
    </div>
  );
}

export default CreateCourse;

